package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public ResultInfo login(String username, String password) {
        //调用mapper查询
        Employee employee = employeeMapper.findByUsername(username);
        if (employee==null){
            return ResultInfo.error("当前用户不存在");
        }
        String passwordwithmd5 = SecureUtil.md5(password);
        if (StringUtils.equals(passwordwithmd5, password)){
            return ResultInfo.error("用户密码错误");
        }
        //3. 查看用户的status是否为0,禁用状态
        if(employee.getStatus()==employee.STATUS_DISABLE){
            return ResultInfo.error("当前用户已被禁用");
        }
        //登录成功，返回
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findByName(String name) {
        return employeeMapper.findByName(name);

    }
    //保存
    @Override
    public void save(Employee employee) {
        //补齐参数
        //雪花算法
        long id = IdUtil.getSnowflake(1, 1).nextId();
        employee.setId(id);
        employee.setPassword(SecureUtil.md5("123"));
        employee.setStatus(Employee.STATUS_ENABLE);
       /*
        employee.setCreateTime(new Date());
        employee.setUpdateTime(new Date());

        employee.setCreateUser(1L);
        employee.setUpdateUser(1L);*/
      employeeMapper.save(employee);
    }

    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);

    }

    @Override
    public void update(Employee employee) {
        //1.设置参数

      /*  //2.设置更新时间
        employee.setUpdateTime(new Date());
        //3.设置更新人
        employee.setUpdateUser(1L);
*/
        employeeMapper.update(employee);

    }
}
